package com.yunhai.ucenter.config.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunhai.common.dto.GlobalException;
import com.yunhai.model.entity.ums.UmsUser;
import com.yunhai.ucenter.mapper.SysUserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<UmsUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq( UmsUser::getUserName, username );
        UmsUser sysUser = userMapper.selectOne(lambdaQueryWrapper);
        if( sysUser == null ){
            throw GlobalException.gen(10001, "账号或密码错误");
        }

        String encodePassword =  new BCryptPasswordEncoder().encode(sysUser.getPassword());
        return  new LoginUser( sysUser.getUserName(), encodePassword);
    }
}
